// Decompiled by DJ v3.11.11.95 Copyright 2009 Atanas Neshkov  Date: 22/03/2011 12:28:32 p.m.
// Home Page: http://members.fortunecity.com/neshkov/dj.html  http://www.neshkov.com/dj.html - Check often for new version!
// Decompiler options: packimports(3) 
// Source File Name:   RecepcionDeComprasImportacionPanel.java

package com.luxsoft.sw3.impap.ui.consultas;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import ca.odell.glazedlists.BasicEventList;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.FilterList;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.gui.TableFormat;
import ca.odell.glazedlists.matchers.CompositeMatcherEditor;
import ca.odell.glazedlists.swing.TextComponentMatcherEditor;

import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.beans.Model;
import com.jgoodies.binding.list.SelectionInList;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
import com.luxsoft.siipap.compras.model.EntradaPorCompra;
import com.luxsoft.siipap.compras.model.RecepcionDeCompra;
import com.luxsoft.siipap.model.Periodo;
import com.luxsoft.siipap.model.Sucursal;
import com.luxsoft.siipap.service.ServiceLocator2;
import com.luxsoft.siipap.swing.browser.AbstractMasterDatailFilteredBrowserPanel;
import com.luxsoft.siipap.swing.form2.AbstractForm;
import com.luxsoft.siipap.swing.form2.DefaultFormModel;
import com.luxsoft.siipap.swing.reports.ReportUtils;
import com.luxsoft.siipap.swing.utils.CommandUtils;
import com.luxsoft.sw3.impap.ui.form.RecepcionDeCompraController;
import com.luxsoft.sw3.impap.ui.form.RecepcionDeCompraForm;

public class RecepcionDeComprasImportacionPanel extends AbstractMasterDatailFilteredBrowserPanel
{
    private static class ReportForm1 extends AbstractForm
    {
        public static class ReportModel extends Model
        {

            public Sucursal getSucursal()
            {
                return sucursal;
            }

            public void setSucursal(Sucursal sucursal)
            {
                Object old = this.sucursal;
                this.sucursal = sucursal;
                firePropertyChange("sucursal", old, sucursal);
            }

            public Date getFecha()
            {
                return fecha;
            }

            public void setFecha(Date fecha)
            {
                Object old = this.fecha;
                this.fecha = fecha;
                firePropertyChange("fecha", old, fecha);
            }

            private Sucursal sucursal;
            private Date fecha;

            public ReportModel()
            {
                fecha = new Date();
            }
        }


        protected JComponent buildFormPanel()
        {
            FormLayout layout = new FormLayout("p,3dlu,70dlu:g", "");
            DefaultFormBuilder builder = new DefaultFormBuilder(layout);
            builder.append("Sucursal", getControl("sucursal"));
            builder.append("Fecha", getControl("fecha"));
            return builder.getPanel();
        }

        protected JComponent createCustomComponent(String property)
        {
            if("sucursal".equals(property))
            {
                List data = ServiceLocator2.getLookupManager().getSucursalesOperativas();
                SelectionInList sl = new SelectionInList(data, model.getModel(property));
                javax.swing.JComboBox box = BasicComponentFactory.createComboBox(sl);
                return box;
            } else
            {
                return null;
            }
        }

        public Sucursal getSucursal()
        {
            return (Sucursal)model.getValue("sucursal");
        }

        public Date getFecha()
        {
            return (Date)model.getValue("fecha");
        }

        public ReportForm1()
        {
            super(new DefaultFormModel(new ReportModel()));
        }
    }


    public RecepcionDeComprasImportacionPanel()
    {
        super(RecepcionDeCompra.class);
        productoFilter = new JTextField(5);
        sucursalFilter = new JTextField(5);
        comentarioFilter = new JTextField(5);
        setTitle("Recepciones de Compras");
    }

    protected void agregarMasterProperties()
    {
        addProperty(new String[] {
            "documento", "fecha", "compra.proveedor.nombre", "remision", "Compra.folio", "compra.fecha", "embarcacion", "embarcacionRef", "contenedores", "embarqueFecha", 
            "ingresoAduana", "autorizacionAduana"
        });
        addLabels(new String[] {
            "Docto", "Fecha", "Proveedor", "Remisi\363n", "Compra", "Fecha C", "Embarcacion", "Emb Ref", "Contenedores", "Emb Fecha", 
            "Ing Aduana", "Aut Aduana"
        });
        installTextComponentMatcherEditor("Com", new String[] {
            "documento"
        });
        installTextComponentMatcherEditor("Remisi\363n", new String[] {
            "remision"
        });
        installTextComponentMatcherEditor("Proveedor", new String[] {
            "compra.proveedor.nombre"
        });
        manejarPeriodo();
    }

    protected void manejarPeriodo()
    {
        periodo = Periodo.getPeriodoConAnteriroridad(6);
    }

    protected TableFormat createDetailTableFormat()
    {
        return GlazedLists.tableFormat(EntradaPorCompra.class, new String[] {
            "sucursal.nombre", "documento", "fecha", "clave", "descripcion", "compraDet.solicitado", "cantidad", "costo", "contenedor", "pallets", 
            "toneladasNeta", "toneladaBruta", "toneladaEstimada"
        }, new String[] {
            "Sucursal", "Docto", "Fecha", "Prod", "Desc", "Solicitado", "Recibido", "costo", "Contenedor", "Pallets", 
            "TON (Net)", "TON (Brt)", "TON (Est)"
        });
    }

    protected void installDetailFilterComponents(DefaultFormBuilder builder)
    {
        super.installDetailFilterComponents(builder);
        builder.append("Producto", productoFilter);
        builder.append("Sucursal", sucursalFilter);
        builder.append("Comentario", comentarioFilter);
    }

    protected EventList decorateDetailList(EventList data)
    {
        EventList editors = new BasicEventList();
        ca.odell.glazedlists.TextFilterator prodFilterator = GlazedLists.textFilterator(new String[] {
            "clave", "descripcion"
        });
        TextComponentMatcherEditor prodEditor = new TextComponentMatcherEditor(productoFilter, prodFilterator);
        editors.add(prodEditor);
        ca.odell.glazedlists.TextFilterator sucFilterator = GlazedLists.textFilterator(new String[] {
            "sucursal.nombre"
        });
        TextComponentMatcherEditor sucEditor = new TextComponentMatcherEditor(sucursalFilter, sucFilterator);
        editors.add(sucEditor);
        ca.odell.glazedlists.TextFilterator comentarioFilterator = GlazedLists.textFilterator(new String[] {
            "comentario"
        });
        TextComponentMatcherEditor comentarioEditor = new TextComponentMatcherEditor(comentarioFilter, comentarioFilterator);
        editors.add(comentarioEditor);
        CompositeMatcherEditor matcherEditor = new CompositeMatcherEditor(editors);
        FilterList detailFilter = new FilterList(data, matcherEditor);
        return detailFilter;
    }

    protected ca.odell.glazedlists.CollectionList.Model createPartidasModel()
    {
        return new ca.odell.glazedlists.CollectionList.Model() {

            public List getChildren(RecepcionDeCompra parent)
            {
                String hql = "from EntradaPorCompra e where e.recepcion.id=?";
                return ServiceLocator2.getHibernateTemplate().find(hql, parent.getId());
            }

            public  List getChildren(Object obj)
            {
                return getChildren((RecepcionDeCompra)obj);
            }

            
        }
;
    }

    protected List findData()
    {
        String hql = "from RecepcionDeCompra r  left join fetch r.compra c left join fetch c.proveedor p where r.fecha between ? and ?";
        Object params[] = {
            periodo.getFechaInicial(), periodo.getFechaFinal()
        };
        return ServiceLocator2.getHibernateTemplate().find(hql, params);
    }

    public Action[] getActions()
    {
        if(actions == null)
            actions = (new Action[] {
                getLoadAction()
                , getViewAction()
                //, getEditAction()
                //, getDeleteAction()
                //, getInsertAction()
                //, addAction("", "cambiarSucursal", "Cambiar sucursal")
                //, CommandUtils.createPrintAction(this, "imprimir")
            });
        return actions;
    }

    protected List createProccessActions()
    {
        List procesos = super.createProccessActions();
        procesos.add(addAction(null, "reportePackingList", "PackingList"));
        procesos.add(addAction(null, "reporteDistribucionDeImportacion", "Reporte de Distribucion"));
        procesos.add(addAction(null, "reporteCosteoDeImportacion", "Costeo de Importacion"));
        procesos.add(addAction("", "entradasPorDia", "Entradas por d\355a"));
        procesos.add(addAction(null, "reportePackingList", "PackingList"));
        return procesos;
    }

    public void reporteDistribucionDeImportacion()
    {
        com.luxsoft.sw3.impap.reportes.reporteDistribucionDeImportacion.run();
    }

    public void reporteCosteoDeImportacion()
    {
        com.luxsoft.sw3.impap.reportes.reporteCosteoDeImportacion.run();
    }

    public void reportePackingList()
    {
        com.luxsoft.sw3.impap.reportes.reportePackingList.run();
    }

    public void imprimir()
    {
        RecepcionDeCompra rec = (RecepcionDeCompra)getSelectedObject();
        if(rec != null)
        {
            Sucursal suc = rec.getSucursal();
            Map parameters = new HashMap();
            parameters.put("ENTRADA", rec.getId());
            parameters.put("SUCURSAL", String.valueOf(suc.getId()));
            ReportUtils.viewReport(ReportUtils.toReportesPath("compras/EntradaPorCompra.jasper"), parameters);
        }
    }

    public void entradasPorDia()
    {
        ReportForm1 form = new ReportForm1();
        form.open();
        if(!form.hasBeenCanceled())
        {
            Map parameters = new HashMap();
            parameters.put("FECHA_ENT", form.getFecha());
            parameters.put("SUCURSAL", form.getSucursal().getId().toString());
            ReportUtils.viewReport(ReportUtils.toReportesPath("compras/RecepDeMercancia.jasper"), parameters);
        }
    }

    protected RecepcionDeCompra doInsert()
    {
        RecepcionDeCompraController controller = new RecepcionDeCompraController();
        RecepcionDeCompraForm form = new RecepcionDeCompraForm(controller);
        form.open();
        if(!form.hasBeenCanceled())
            return controller.persist();
        else
            return null;
    }

    protected RecepcionDeCompra doEdit(RecepcionDeCompra bean)
    {
        if(bean.getFacturada() != null)
            return null;
        bean = reload(bean);
        RecepcionDeCompraController controller = new RecepcionDeCompraController(bean);
        RecepcionDeCompraForm form = new RecepcionDeCompraForm(controller);
        form.open();
        if(!form.hasBeenCanceled())
            return controller.persist();
        else
            return null;
    }

    public boolean doDelete(RecepcionDeCompra bean)
    {
        if(bean.getFacturada() != null)
        {
            return false;
        } else
        {
            ServiceLocator2.getUniversalDao().remove(RecepcionDeCompra.class, bean.getId());
            return true;
        }
    }

    public void cambiarSucursal()
    {
        if(!detailSelectionModel.getSelected().isEmpty())
        {
            Sucursal sel = (Sucursal)JOptionPane.showInputDialog(getControl(), "Seleccione la sucursal", "Sucursales", 1, null, ServiceLocator2.getLookupManager().getSucursalesOperativas().toArray(), null);
            if(sel != null)
            {
                int min = detailSelectionModel.getMinSelectionIndex();
                int max = detailSelectionModel.getMaxSelectionIndex();
                for(int i = min; i <= max; i++)
                {
                    EntradaPorCompra entrada = (EntradaPorCompra)detailSortedList.get(i);
                    entrada.setSucursal(sel);
                    entrada = (EntradaPorCompra)ServiceLocator2.getUniversalDao().save(entrada);
                    detailSortedList.set(i, entrada);
                }

            }
        }
    }

    private RecepcionDeCompra reload(RecepcionDeCompra rec)
    {
        String hql = "from RecepcionDeCompra r  left join fetch r.partidas rr left join fetch r.compra c left join fetch c.proveedor p where r.id=?";
        List res = ServiceLocator2.getHibernateTemplate().find(hql, rec.getId());
        return res.isEmpty() ? null : (RecepcionDeCompra)res.get(0);
    }


    private JTextField productoFilter;
    private JTextField sucursalFilter;
    private JTextField comentarioFilter;
}
